import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Form,
  Input,
  Button,
  Checkbox,
  message,
  Radio,
  Tree,
  Tag,
  Modal,
  Tabs,
  Card,
} from 'antd';

import TagsBlock from '@/pages/features/userPermission/user/add/components/tagsBlock';
import UserManagement from '@/components/UserManagement';

import request from 'umi-request';

import {
  roleAuthorize,
  getAuthorizedUserByRoleId,
} from '@/services/userControl';
import { history } from 'umi';
import styles from './index.less';

const AuthorizationPage = (props: any) => {
  const { state } = props.location;
  console.log(props);
  const formRef = useRef<any>();
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [uerManagementTags, setuerManagementTags] = useState([]);
  const [userTags, setuserTags] = useState([]);
  const [roleMsg, setRoleMsg] = useState({
    allRoleList: [],
    checkRoleList: [],
    checkRoleKeys: [],
  });
  useEffect(() => {
    initPageData();
  }, []);
  const initPageData = async () => {
    getAuthorizedUser();
    formRef.current.setFieldsValue({
      name: state.name,
      description: state.description,
    });
  };
  const getAuthorizedUser = async () => {
    const res = await getAuthorizedUserByRoleId(state.roleId);
    setuerManagementTags(res.data);
    setuserTags(formatUesrTagsData(res.data));
  };
  const handleSubmit = useCallback((data: any) => {
    console.log(data, 'handleSubmit');
    setuserTags(formatUesrTagsData(data.tags));
    setIsModalVisible(false);
  }, []);
  const handleCancel = useCallback(() => {
    setIsModalVisible(false);
  }, []);
  const removeCurrentTagHandle = (val: string) => {
    const newTags = userTags.filter(
      (item: { value: string }) => item.value !== val,
    );
    setuserTags(newTags);
  };
  const formatUesrTagsData = (data: any) => {
    let _data = [];
    if (Array.isArray(data) && data.length > 0) {
      for (const item of data) {
        _data.push({
          value: item.id,
          label: item.name,
        });
      }
    }
    return _data;
  };

  const saveData = async () => {
    console.log(state.roleId);
    let msg = {
      roleId: state.roleId,
      arrUserId: userTags.map((item) => item.value),
    };
    const res = await roleAuthorize(msg);
    if (res.code === 200) {
      message.success('保存成功');
      setTimeout(() => {
        history.push({
          pathname: '/features/userPermission/role',
        });
      }, 1000);
    }
  };

  return (
    <>
      <UserManagement
        isModalVisible={isModalVisible}
        handleSubmit={handleSubmit}
        handleCancel={handleCancel}
        userList={uerManagementTags}
        type={2}
      ></UserManagement>
      <Card title={'授权用户'}>
        <Form ref={formRef}>
          <div className={styles.formContainer}>
            <div className={styles.flexRow}>
              <Form.Item
                name="name"
                label="角色名"
                rules={[{ required: true, message: '请输入角色名!' }]}
              >
                <Input disabled placeholder="请输入角色名"></Input>
              </Form.Item>
              <Form.Item
                name="description"
                label="角色描述"
                rules={[{ required: true, message: '请输入角色描述!' }]}
              >
                <Input disabled placeholder="请输入角色描述"></Input>
              </Form.Item>
            </div>
            <div className={styles.flexRow}>
              <Form.Item name="selectUser" label="选择用户">
                <TagsBlock
                  dataSource={userTags}
                  removeCurrentTag={removeCurrentTagHandle}
                ></TagsBlock>
                <Button
                  size="small"
                  onClick={() => {
                    setIsModalVisible(true);
                  }}
                >
                  添加
                </Button>
              </Form.Item>
            </div>
          </div>
        </Form>
      </Card>
      <div className={styles.footBtnGroup}>
        <Button type="primary" htmlType="submit" onClick={saveData}>
          保存并提交
        </Button>
      </div>
    </>
  );
};

export default AuthorizationPage;
